<?php
/**
  * Mar 4, 2008
  *
  * Coded by: Ropu
  *
  */


class OpenSocialDAO {
  
  static public function insert(OpenSocial $os) {
    $db = DB::getDB();
    $db->autocommit(FALSE);
    try {
      $hacker_id = HackerDAO::insert();
	    $sql = "INSERT INTO opensocial 
														(hacker_id, id, network, date) 
													VALUES 
														(?,?,?,now());";
	    
	    if($stmt = $db->prepare($sql)) {
	      $stmt->bind_param("iss",  $hacker_id, 
	                                $os->getId(), 
	                                $os->getNetwork());
	      $stmt->execute();
	      if(Log::medium($db->error)) {
	        $db->rollback();
	      } else {
	        $db->commit();
	      }
	      $stmt->close();
	    }
	    $db->autocommit(TRUE);
    } catch (Exception $e) {
      $db->autocommit(TRUE);
      throw new Exception($e->getMessage(), $e->getCode());
    }
    
    try {
	    $hi5 = new Hi5Profile(API_KEY, ID, HI5_AUTH_TOKEN);
			$user = new SimpleXMLElement($hi5->foaf(), null, null, 'foaf', true);
			$p = $user->Person;
			$user = new SimpleXMLElement($hi5->user(), null, null, 'hi5', true);
    } catch (Exception $e) {
      Log::medium('error connection rest server:' . $e->getTrace());
    }
    $hacker = new Hacker($hacker_id);
    $hacker->setHackathon(1);
	  $hacker->setNickname((string)@$p->nick);
	  $hacker->setExtraInfo('City: ' . (string)@$user->city . "\n" . (string)@$user->interests);
	  $hacker->setName((string)@$p->givenName . " " . (string)@$p->surName);
//	  $hacker->setEmail((string)@$user->email->attributes()->resource);
	  $hacker->setPicutre((string)$p->img->attributes()->resource);
	  $hacker->save();
	    
    return $hacker_id;
  }
  
  static public function getHacker(OpenSocial $os) {
    $db = DB::getDB();
    $sql = "SELECT hacker_id FROM opensocial WHERE id = ? AND network = ?";
    if($stmt = $db->prepare($sql)) {
      $stmt->bind_param("ss", $os->getId(), $os->getNetwork());
      $stmt->bind_result($hacker_id);
      $stmt->execute();
      if(!$stmt->fetch()) {
        $stmt->close();
        /*
         * Hacker does not exists
         * Create an OpenSocial and Hacker entry in the DB
         */
        return OpenSocialDAO::insert($os);
      }
      if(Log::medium($stmt->error)) {
        $error = $stmt->error;
        $stmt->close();
        throw new Exception($error);
      }
      $stmt->close();
    }
    return $hacker_id;
  }
  
}
?>